<template>
  <div>
    <van-form @submit="onSubmit">
      <van-field
        v-model="username"
        name="userName"
        label="用户名"
        placeholder="请输入您的用户名"
        :rules="[
          {
            pattern: /^[a-zA-Z_$][a-zA-Z0-9_-]{4,10}$/,
            message: '请以非数字开头',
          },
        ]"
      />
      <van-field
        v-model="password"
        type="password"
        name="passWord"
        label="密码"
        placeholder="请输入您的密码"
        :rules="[
          { pattern: /^[a-zA-Z0-9_-]{4,16}$/, message: '请输入4-16位密码' },
        ]"
      />
      <van-field
        v-model="passWordAgain"
        type="password"
        name="passWordAgain"
        label="确认密码"
        placeholder="请输入您的密码"
        :rules="[{ validator, message: '请保持两次密码输入一致' }]"
      />
      <van-field
        v-model="phonenumber"
        name="phonenumber"
        label="手机号"
        placeholder="请填您的手机号"
        :rules="[
          {
            pattern: /^1[3-9]\d{9}$/,
            message: '您输入的手机号有误',
          },
        ]"
      />
      <van-field name="sex" label="单选框">
        <template #input>
          <van-radio-group v-model="sex" direction="horizontal">
            <van-radio name="0">男</van-radio>
            <van-radio name="1">女</van-radio>
          </van-radio-group>
        </template>
      </van-field>
      <div style="margin: 16px">
        <van-button round block type="info" native-type="submit"
          >提交</van-button
        >
      </div>
    </van-form>
  </div>
</template>
<script>
import { register } from "@service/UserService";
export default {
  data() {
    return {
      username: "",
      password: "",
      phonenumber: "",
      passWordAgain: "",
      sex: "0",
    };
  },
  methods: {
    validator(val) {
      return this.password === val;
    },
    async onSubmit(val) {
      const obj = {
        userName: val.userName,
        password: val.passWord,
        phonenumber: val.phonenumber,
        sex: val.sex,
      };
      const { code, msg } = await register(obj);
      console.log(code, msg);
      if (code == 200) {
        this.$emit("changeActive", 0);
        this.$toast.success(msg);
        this.username = "";
        this.password = "";
        this.phonenumber = "";
        this.passWordAgain = "";
      } else {
        this.$toast.fail(msg);
      }
    },
  },
};
</script>
